package com.yt.user.service;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.yt.user.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.user.mapper.CustomerInfoMapper;
import com.yt.user.models.service.ICustomerInfoService;
import com.yt.user.models.bo.CustomerInfoSaveBO;
import com.yt.user.models.dto.CustomerInfoDTO;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 客户信息控制器
 *
 * @author yzz
 * @Date 2025-10-22 09:43:50
 */
@DubboService
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfoDTO> implements ICustomerInfoService{
    
    // 使用原子整数确保线程安全的序列号
    private static final AtomicInteger sequence = new AtomicInteger(0);
    // 记录最后生成ID的日期，用于重置序列号
    private static String lastDate = "";
    // 添加锁确保生成ID的线程安全
    private static final Lock lock = new ReentrantLock();

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(CustomerInfoSaveBO saveBO) {
        CustomerInfoDTO dto = new CustomerInfoDTO();
        // 手动映射字段，确保所有字段都被正确复制
        if(saveBO.getId() != null) {
            dto.setCustomerId(saveBO.getId());
        } else {
            // 生成有序的ID
            dto.setCustomerId(generateSequentialId());
        }
        
        // 使用setter方法手动设置每个字段
        dto.setName(saveBO.getName());
        dto.setType(saveBO.getType());
        dto.setCommunity(saveBO.getCommunity());
        dto.setManager(saveBO.getManager());
        dto.setSpecialist(saveBO.getSpecialist());
        dto.setCommunityManager(saveBO.getCommunityManager());
        dto.setIndustryId(saveBO.getIndustryId());
        
        // 手动设置创建时间和更新时间
        Date now = new Date();
        dto.setCreateTime(now);
        dto.setUpdateTime(now);
        
        boolean result = this.insert(dto);
        return result;
    }
    
    @Override
    public CustomerInfoDTO addAndReturn(CustomerInfoSaveBO saveBO) {
        CustomerInfoDTO dto = new CustomerInfoDTO();
        // 手动映射字段，确保所有字段都被正确复制
        if(saveBO.getId() != null) {
            dto.setCustomerId(saveBO.getId());
        } else {
            // 生成有序的ID
            dto.setCustomerId(generateSequentialId());
        }
        
        // 使用setter方法手动设置每个字段
        dto.setName(saveBO.getName());
        dto.setType(saveBO.getType());
        dto.setCommunity(saveBO.getCommunity());
        dto.setManager(saveBO.getManager());
        dto.setSpecialist(saveBO.getSpecialist());
        dto.setCommunityManager(saveBO.getCommunityManager());
        dto.setIndustryId(saveBO.getIndustryId());
        
        // 手动设置创建时间和更新时间
        Date now = new Date();
        dto.setCreateTime(now);
        dto.setUpdateTime(now);
        
        boolean result = this.insert(dto);
        if (result) {
            return dto;
        }
        return null;
    }
    
    /**
     * 生成有序ID：日期+序列号
     * 格式：yyyyMMddXXXXXX (其中XXXXXX是当天的序列号，不足6位前面补0)
     * @return 有序ID字符串
     */
    private String generateSequentialId() {
        lock.lock(); // 加锁确保线程安全
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String currentDate = dateFormat.format(new Date());
            
            // 如果日期变了，重置序列号
            if (!currentDate.equals(lastDate)) {
                sequence.set(0);
                lastDate = currentDate;
            }
            
            // 获取序列号并递增
            int seq = sequence.incrementAndGet();
            
            // 格式化序列号为6位数字，不足的前面补0
            String sequenceStr = String.format("%06d", seq);
            
            // 组合日期和序列号，确保总长度不超过20字符
            String id = currentDate + sequenceStr;
            
            // 如果超过20字符，截取前20位
            if (id.length() > 20) {
                id = id.substring(0, 20);
            }
            
            // 检查生成的ID是否已存在，如果存在则重新生成
            while (this.selectById(id) != null) {
                seq = sequence.incrementAndGet();
                sequenceStr = String.format("%06d", seq);
                id = currentDate + sequenceStr;
                if (id.length() > 20) {
                    id = id.substring(0, 20);
                }
            }
            
            return id;
        } finally {
            lock.unlock(); // 解锁
        }
    }
    
    @Override
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }
    
    @Override
    public CustomerInfoDTO selectById(Serializable id) {
        return super.selectById(id);
    }
}